package com.ielts.fragment;

import vn.com.baseapplication.BaseFragment;
import vn.com.baseapplication.constant.BaseConstant;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.ielts.IeltsConstant;
import com.ielts.activity.IeltsApplication;
import com.ielts.activity.MainActivity;
import com.ielts.activity.R;
import com.ielts.activity.TopicActivity;
import com.ielts.fragment.adapter.TopicAdapter;
import com.ielts.model.ItemTopics;
import com.ielts.model.Topics;
import com.ielts.services.IeltsUrl;

public class AllFragment extends BaseFragment implements OnItemClickListener,
		OnClickListener {

	private static final String KEY_CONTENT = "AllFragment:Content";
	MainActivity activity;
	private TopicAdapter listAllAdapter;
	private PullToRefreshListView pulllistAll;
	private ListView listAll;
	private View loading;
	private View layoutHeader;
	private TextView tvHeader;
	Handler mHandler = new Handler();

	String urlAllTopic = "";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		if ((savedInstanceState != null)
				&& savedInstanceState.containsKey(KEY_CONTENT)) {

		}

	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		activity = (MainActivity) getActivity();
		ViewGroup viewGroup = (ViewGroup) view;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		activity = (MainActivity) getActivity();
		mActivity = activity;
		View layout = inflater.inflate(R.layout.fragment_all, null);

		layoutHeader = (View) layout.findViewById(R.id.layout_header);
		pulllistAll = (PullToRefreshListView) layout.findViewById(R.id.list);
		listAll = pulllistAll.getRefreshableView();
		loading = layout.findViewById(R.id.loading_all);
		tvHeader = (TextView) layout.findViewById(R.id.header_tv_year);
		listAllAdapter = new TopicAdapter(getActivity(), activity.listIelts);
		listAll.setAdapter(listAllAdapter);
		listAll.setOnItemClickListener(this);

		layoutHeader.setOnClickListener(this);

		pulllistAll.setOnRefreshListener(new OnRefreshListener<ListView>() {
			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				// Do work to refresh the list here.
				getAllTopics();
			}
		});

		return layout;
	}

	@Override
	public void onResume() {
		super.onResume();
		getAllTopics();
	}

	public void getAllTopics() {
		String year = IeltsApplication.getInstance().getValue(
				IeltsConstant.KEY_YEAR, IeltsConstant.KEY_YEAR_DEF);
		String urlAllTopic = IeltsUrl.URL_TOPIC_ALL;
		urlAllTopic += "?year=" + year;
		urlAllTopic += "&custId=" + IeltsApplication.getInstance().getValue(IeltsConstant.KEY_USER_ID, IeltsConstant.KEY_USER_ID_DEF);

		this.urlAllTopic = urlAllTopic;
		network.get(IeltsConstant.GET_ALL_TOPICS_FROM_SERVER, getActivity(),
				urlAllTopic);
		// Log.e("GET ALL TOPIC", "url: " + urlAllTopic);

		tvHeader.setText(IeltsApplication.getInstance().getValue(
				IeltsConstant.KEY_YEAR, IeltsConstant.KEY_YEAR_DEF));
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}

	@Override
	public void onNetSuccess(int requestId, final String response) {
		super.onNetSuccess(requestId, response);
		activity.onNetSuccess(requestId, response);
		setLoading(false);
		
		switch (requestId) {
		case IeltsConstant.GET_ALL_TOPICS_FROM_SERVER:
			if (response != null && !response.equals(""))
				network.setCache(IeltsUrl.URL_GUILD, response);
			onNetSuccessCache(requestId, response);

			String urlAllTopic = IeltsUrl.URL_TOPIC_ALL;
			String year = IeltsApplication.getInstance().getValue(
					IeltsConstant.KEY_YEAR, IeltsConstant.KEY_YEAR_DEF);
			urlAllTopic += "?year=" + year;
			urlAllTopic += "&custId=" + IeltsApplication.getInstance().getValue(IeltsConstant.KEY_USER_ID, IeltsConstant.KEY_USER_ID_DEF);
			network.setCache(urlAllTopic, response);
			
			
			break;

		default:
			break;
		}
		if (mActivity != null)
			mActivity.runOnUiThread(new Runnable() {

				@Override
				public void run() {
					pulllistAll.onRefreshComplete();
				}
			});
	}

	@Override
	public void onNetSuccessCache(int requestId, final String response) {
		activity.onNetSuccessCache(requestId, response);
		setLoading(false);
		switch (requestId) {
		case IeltsConstant.GET_ALL_TOPICS_FROM_SERVER:
			// Log.e("GET ALL TOPIC", "all topic: " + response);

			activity.runOnUiThread(new Runnable() {

				@Override
				public void run() {
					Gson gson = new Gson();
					Topics topic = gson.fromJson(response, Topics.class);
					activity.listIelts.clear();
					for (ItemTopics item : topic.topics) {
						activity.listIelts.add(item);
					}
					listAllAdapter.notifyDataSetChanged();
					tvHeader.setText(IeltsApplication.getInstance().getValue(
							IeltsConstant.KEY_YEAR, IeltsConstant.KEY_YEAR_DEF));

					Intent intent = new Intent();
					intent.putExtra(BaseConstant.MSG_FLAG, IeltsConstant.REFRESH_DATA + "");
					sendBaseBroadcast(activity, intent);
				}
			});

			break;

		default:
			break;
		}
		
	}

	@Override
	public void onNetLoading(int requestId) {
		super.onNetLoading(requestId);
		// setLoading(true);
	}

	@Override
	public void onNetFailed(int requestId, String error) {
		super.onNetFailed(requestId, error);
		setLoading(false);
	}

	@Override
	public void onNetTimeOut(int requestId, Throwable error) {
		super.onNetTimeOut(requestId, error);
		setLoading(false);
	}

	public void setLoading(final boolean isLoading) {

		if (isLoading) {
			activity.runOnUiThread(new Runnable() {

				@Override
				public void run() {
					loading.setVisibility(View.VISIBLE);
				}
			});
		} else {
			mHandler.postDelayed(new Runnable() {

				@Override
				public void run() {
					loading.setVisibility(View.GONE);
				}
			}, 1000);
		}

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// position from 1. PullToRefresh view: 0
		ItemTopics itemTopic = listAllAdapter.getItem(position-1);
		Intent topicIntent = new Intent(getActivity(), TopicActivity.class);
		topicIntent.putExtra(BaseConstant.MSG_DATA, itemTopic);
		startActivity(topicIntent);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.layout_header:
			((MainActivity) activity).setupSelectYearDialog().show();
			break;

		default:
			break;
		}
	}
}
